﻿namespace MiniJob.Worker.Jobs;

/// <summary>
/// 广播Job
/// </summary>
public abstract class BroadcastJob : Job
{
    /// <summary>
    /// 在所有节点广播执行前执行，只会在一台机器执行一次
    /// </summary>
    /// <param name="context">任务上下文</param>
    /// <returns></returns>
    public virtual Task<JobResult> PreProcessAsync(JobContext context)
    {
        return Task.FromResult(new JobResult(true));
    }

    /// <summary>
    /// 在所有节点广播执行完成后执行，只会在一台机器执行一次
    /// </summary>
    /// <param name="context">任务上下文</param>
    /// <returns></returns>
    public virtual Task<JobResult> PostProcessAsync(JobContext context, List<JobResult> taskResults)
    {
        return Task.FromResult(DefaultResult(taskResults));
    }

    public static JobResult DefaultResult(List<JobResult> taskResults)
    {
        long succeed = 0, failed = 0;
        foreach (var result in taskResults)
        {
            if (result.Success)
                succeed++;
            else
                failed++;
        }
        return new JobResult(failed == 0, $"succeed:{succeed}, failed:{failed}");
    }
}
